package fr.enseirb.mycub.activity.component;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.location.Location;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;

import fr.enseirb.mycub.PrefManager;
import fr.enseirb.mycub.activity.AbstractPreferencesActivity;
import fr.enseirb.mycub.activity.MainActivity;
import fr.enseirb.mycub.component.map.bike.MyLocationOverlay;
import fr.enseirb.mycub.service.LocationService;
import fr.enseirb.mycub.service.LocationService.LocationBinder;

public class LocationServiceComponent {

	
	private LocationService mService = null;
	private boolean mBound = false;
	private MainActivity currentActivity;
	public ServiceConnection mConnection;
	
	public LocationServiceComponent(MainActivity activity){
		currentActivity = activity;
		
		mConnection = new ServiceConnection() {

			@Override
			public void onServiceConnected(ComponentName className, IBinder service) {
				// We've bound to LocalService, cast the IBinder and get
				// LocalService instance
				LocationBinder binder = (LocationBinder) service;
				mService = binder.getService();
				mBound = true;
				mService.addListener(currentActivity);
			}

			@Override
			public void onServiceDisconnected(ComponentName arg0) {
				mBound = false;
			}
		};
	}
	
	public void onResume(MainActivity activity){
		currentActivity = activity;
		if (PrefManager.mgr.getBoolean(
				AbstractPreferencesActivity.LOCATION_PREFERENCE, true)) {
			Log.i("LocationServiceComponent","bind service");
			activity.startService(new Intent(activity, LocationService.class));
			Intent intent = new Intent(activity, LocationService.class);
			activity.bindService(intent, mConnection, 0);
		}	
	}
	
	public boolean isBound(){
		return mBound;
	}
	
	public void onPause(){
		mService.removeListener(currentActivity);
		mBound = false;
		currentActivity.unbindService(mConnection);
		Log.i("LocationServiceComponent","UNBINDED service");
	}
	
	public Location getMyLocation(){
		return mService.getMyLocation();
	}
	
	
}
